/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Sales;

import entity.Credit;
import entity.Customer;
import entity.Employee;
import entity.Invoice;
import entity.Job;
import entity.Payment;
import entity.PurchaseItem;
import entity.PurchaseOrder;
import entity.Quotation;
import entity.QuotationItem;
import entity.SalesOrder;
import entity.TrackingItem;
import entity.Warehouse;
import java.io.Serializable;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import managedbean.EmailManager;
import managedbean.UserSessionManagerBean;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import session.stateless.CreditSessionBeanLocal;
import session.stateless.CustomerSessionBeanLocal;
import session.stateless.EmployeeSessionBeanLocal;
import session.stateless.JobSessionBeanLocal;
import session.stateless.LogSessionBeanLocal;
import session.stateless.MessageSessionBeanLocal;
import session.stateless.NoticeSessionBeanLocal;
import session.stateless.ProductionScheduleSessionBeanLocal;
import session.stateless.PurchaseOrderSessionBeanLocal;
import session.stateless.SalesHistorySessionBeanLocal;
import session.stateless.SalesOrderSessionBeanLocal;
import session.stateless.WarehouseSessionBeanLocal;

/**
 *
 * @author Wx
 */
@ManagedBean(name = "salesOrderManagerBean")
@RequestScoped
public class SalesOrderManagerBean implements Serializable {

    @EJB
    SalesOrderSessionBeanLocal salesOrderSessionBeanLocal;
    @EJB
    JobSessionBeanLocal jobSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @EJB
    private PurchaseOrderSessionBeanLocal purchaseOrderSessionBeanLocal;
    @EJB
    private NoticeSessionBeanLocal noticeSessionBeanLocal;
    @EJB
    private EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @EJB
    private MessageSessionBeanLocal messageSessionBeanLocal;
    @EJB
    private SalesHistorySessionBeanLocal salesHistorySessionBeanLocal;
    @EJB
    private CreditSessionBeanLocal creditSessionBeanLocal;
    @EJB
    private CustomerSessionBeanLocal customerSessionBeanLocal;
    @EJB
    private ProductionScheduleSessionBeanLocal productionScheduleSessionBeanLocal;
    @EJB
    private WarehouseSessionBeanLocal warehouseSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private String loadPurchaseOrdersPage;
    private PurchaseOrder selectedPurchaseOrder;
    private List<PurchaseOrder> purchaseOrders;
    private List<PurchaseOrder> purchaseOrders2;
    private int purchaseOrdersCount;
    private int purchaseOrdersCount2;
    private String loadAddSalesOrderPage;
    private Quotation selectedQuotation;
    private Job selectedJob;
    private String loadSalesOrdersPage;
    private List<SalesOrder> salesOrders;
    private int salesOrdersSize;
    private String remark;
    private SalesOrder selectedSalesOrder;
    private String loadViewSalesOrderPage;
    private String loadViewPurchaseOrderPage;
    private String loadSearchPurchaseOrdersPage;
    private String loadCancelSalesOrderPage;
    private String loadMySalesOrders;
    private String loadSalesOrders;
    private String loadUpdateSalesorder;
    private List<SalesOrder> salesOrders2 = new ArrayList<SalesOrder>();
    private Customer selectedCustomer;
    private PurchaseItem selectedPurchaseItem;
    private List<PurchaseItem> purchaseItems = new ArrayList<PurchaseItem>();
    private String cancelReason = "";
    private List<TrackingItem> trackingItems = new ArrayList<TrackingItem>();
    private Boolean toApprove = true;
    private Boolean toReject = true;
    private DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    private ArrayList<TrackingItem> tis = new ArrayList<TrackingItem>();
    private String customerEmail;
    private String salesOrderNumber;

    /** Creates a new instance of SalesorderManagerBean */
    public SalesOrderManagerBean() {
    }

    // <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @return the selectedPurchaseOrder
     */
    public PurchaseOrder getSelectedPurchaseOrder() {
        return selectedPurchaseOrder;
    }

    /**
     * @param selectedPurchaseOrder the selectedPurchaseOrder to set
     */
    public void setSelectedPurchaseOrder(PurchaseOrder selectedPurchaseOrder) {
        this.selectedPurchaseOrder = selectedPurchaseOrder;
    }

    /**
     * @return the purchaseOrders
     */
    public List<PurchaseOrder> getPurchaseOrders() {
        return purchaseOrders;
    }

    /**
     * @param purchaseOrders the purchaseOrders to set
     */
    public void setPurchaseOrders(List<PurchaseOrder> purchaseOrders) {
        this.purchaseOrders = purchaseOrders;
    }

    /**
     * @return the loadUpdateSalesorder
     */
    public String getLoadUpdateSalesorder() {
        try {
            selectedSalesOrder = (SalesOrder) userSessionManagerBean.getSelectedItem();
            selectedPurchaseOrder = selectedSalesOrder.getJob().getPurchaseOrder();
            selectedPurchaseOrder.setPurchaseItems(purchaseOrderSessionBeanLocal.sortPurchaseItems(new ArrayList(selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems())));

            Warehouse wh = warehouseSessionBeanLocal.getWarehouse(Long.parseLong("1000"));
            ArrayList<Date> dates = productionScheduleSessionBeanLocal.getUpdatedPurchaseItemsDates(wh, new ArrayList(selectedPurchaseOrder.getPurchaseItems()),
                    productionScheduleSessionBeanLocal.getProductionSchedules());

            for (int i = 0; i < selectedPurchaseOrder.getPurchaseItems().size(); i++) {
                selectedPurchaseOrder.getPurchaseItems().get(i).setRequestDate(dates.get(i));
            }




        } catch (Exception exception) {
            try {
                System.out.println(exception.toString());
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchJob.xhtml");
            } catch (Exception ex) {
            }
        }

        return null;
    }

    /**
     * @return the loadPurchaseOrdersPage
     */
    public String getLoadPurchaseOrdersPage() {
        setPurchaseOrders(salesOrderSessionBeanLocal.getPurchaseOrders(
                userSessionManagerBean.getSelectedJob().getCustomer().getCustId(), "Pending"));

        this.setPurchaseOrdersCount(purchaseOrders.size());
//        createSalesOrderButtonStatus = true;

        return null;
    }

    /**
     * @param loadPurchaseOrdersPage the loadPurchaseOrdersPage to set
     */
    public void setLoadPurchaseOrdersPage(String loadPurchaseOrdersPage) {
        this.loadPurchaseOrdersPage = loadPurchaseOrdersPage;
    }

    /**
     * @return the purchaseOrdersCount
     */
    public int getPurchaseOrdersCount() {
        return purchaseOrdersCount;
    }

    /**
     * @param purchaseOrdersCount the purchaseOrdersCount to set
     */
    public void setPurchaseOrdersCount(int purchaseOrdersCount) {
        this.purchaseOrdersCount = purchaseOrdersCount;
    }

    /**
     * @return the remark
     */
    public String getRemark() {
        return remark;
    }

    /**
     * @param remark the remark to set
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }

    /**
     * @param loadAddSalesOrderPage the loadAddSalesOrderPage to set
     */
    public void setLoadAddSalesOrderPage(String loadAddSalesOrderPage) {
        this.loadAddSalesOrderPage = loadAddSalesOrderPage;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the selectedQuotation
     */
    public Quotation getSelectedQuotation() {
        return selectedQuotation;
    }

    /**
     * @param selectedQuotation the selectedQuotation to set
     */
    public void setSelectedQuotation(Quotation selectedQuotation) {
        this.selectedQuotation = selectedQuotation;
    }

    /**
     * @return the selectedJob
     */
    public Job getSelectedJob() {
        return selectedJob;
    }

    /**
     * @param selectedJob the selectedJob to set
     */
    public void setSelectedJob(Job selectedJob) {
        this.selectedJob = selectedJob;
    }

    /**
     * @param loadSalesOrdersPage the loadSalesOrdersPage to set
     */
    public void setLoadSalesOrdersPage(String loadSalesOrdersPage) {
        this.loadSalesOrdersPage = loadSalesOrdersPage;
    }

    /**
     * @return the salesOrders
     */
    public List<SalesOrder> getSalesOrders() {
        return salesOrders;
    }

    /**
     * @param salesOrders the salesOrders to set
     */
    public void setSalesOrders(List<SalesOrder> salesOrders) {
        this.salesOrders = salesOrders;
    }

    /**
     * @return the salesOrdersSize
     */
    public int getSalesOrdersSize() {
        return salesOrdersSize;
    }

    /**
     * @param salesOrdersSize the salesOrdersSize to set
     */
    public void setSalesOrdersSize(int salesOrdersSize) {
        this.salesOrdersSize = salesOrdersSize;
    }

    /**
     * @return the selectedSalesOrder
     */
    public SalesOrder getSelectedSalesOrder() {
        return selectedSalesOrder;
    }

    /**
     * @param selectedSalesOrder the selectedSalesOrder to set
     */
    public void setSelectedSalesOrder(SalesOrder selectedSalesOrder) {
        this.selectedSalesOrder = selectedSalesOrder;
    }

    /**
     * @param loadViewPurchaseOrderPage the loadViewPurchaseOrderPage to set
     */
    public void setLoadViewPurchaseOrderPage(String loadViewPurchaseOrderPage) {
        this.loadViewPurchaseOrderPage = loadViewPurchaseOrderPage;
    }

    /**
     * @return the purchaseOrders2
     */
    public List<PurchaseOrder> getPurchaseOrders2() {
        return purchaseOrders2;
    }

    /**
     * @param purchaseOrders2 the purchaseOrders2 to set
     */
    public void setPurchaseOrders2(List<PurchaseOrder> purchaseOrders2) {
        this.purchaseOrders2 = purchaseOrders2;
    }

    /**
     * @param loadSearchPurchaseOrdersPage the loadSearchPurchaseOrdersPage to set
     */
    public void setLoadSearchPurchaseOrdersPage(String loadSearchPurchaseOrdersPage) {
        this.loadSearchPurchaseOrdersPage = loadSearchPurchaseOrdersPage;
    }

    /**
     * @return the purchaseOrdersCount2
     */
    public int getPurchaseOrdersCount2() {
        return purchaseOrdersCount2;
    }

    /**
     * @param purchaseOrdersCount2 the purchaseOrdersCount2 to set
     */
    public void setPurchaseOrdersCount2(int purchaseOrdersCount2) {
        this.purchaseOrdersCount2 = purchaseOrdersCount2;
    }

    //</editor-fold>
    public void next(ActionEvent e) {
        try {
            if (userSessionManagerBean.getSelectedPurchaseOrder() != null) {
                userSessionManagerBean.setSelectedPurchaseOrder(selectedPurchaseOrder);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/addSalesOrder.xhtml"); //redirect to addSalesOrder.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a purchase order before continuing.", ""));
            }

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void back(ActionEvent e) {
        try {
            if (e.getComponent().getId().equals("btnBackToQuotation")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/quotation.xhtml"); //go back to quotation.xhtml
            } else if (e.getComponent().getId().equals("btnBackToPurchaseOrders")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/updateJob.xhtml"); //go back to searchPurchaseOrders.xhtml
            } else if (e.getComponent().getId().equals("btnBackFromMySalesOrders")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchCustomers.xhtml?request=mySalesOrders"); //go back to searchCustomers.xhtml
            } else if (e.getComponent().getId().equals("btnBackFromSalesOrders")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchCustomer.xhtml?request=salesOrders"); //go back to searchCustomers.xhtml
            } else {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/purchaseOrders.xhtml"); //go back to purchaseOrders.xhtml
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void viewSalesOrder(ActionEvent e) {
        try {
            if (userSessionManagerBean.getSelectedSalesOrder() != null) {
                userSessionManagerBean.setSelectedSalesOrder(selectedSalesOrder);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/viewSalesOrder.xhtml"); //redirect to viewSalesOrder.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a sales order before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void approveSalesOrder(ActionEvent e) {
        try {
            if (selectedSalesOrder.getJob().getCustomer().getCredit() != null) { //if customer has credit information already
                salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), "Pending Credit Check");
                salesOrderSessionBeanLocal.updateQuotation(selectedQuotation.getId(), "Approved");
                purchaseOrderSessionBeanLocal.updatePurchaseOrder(selectedPurchaseOrder.getId(), "Approved");

                for (PurchaseItem poi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
                    salesHistorySessionBeanLocal.addSalesHistory(poi);
                }

                TrackingItem ti = new TrackingItem();
                ti.setDescription("Sales Order Approved");
                salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), ti);

                logSessionBeanLocal.addLog("Sales order approval", "Sales order approved: " + selectedSalesOrder.getId(), "viewSalesOrder.xhtml", userSessionManagerBean.getUserId());
                ArrayList<String> al = new ArrayList<String>();
                al.add("Sales order approved");
                al.add("You have successfully approved a sales order");
                al.add("Click on the link to return to ");
                al.add("continue");
                al.add("Web_Sales/searchSalesOrders.xhtml");
                userSessionManagerBean.setSelectedItem(al);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/success.xhtml");
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Customer does not have a credit account yet, "
                        + "please proceed to create a credit account for him before continuing.", ""));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void rejectSalesOrder(ActionEvent e) {
        try {
            salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), "Rejected");

            logSessionBeanLocal.addLog("Sales order approval", "Sales order rejected: " + selectedSalesOrder.getId(), "viewSalesOrder.xhtml", userSessionManagerBean.getUserId());

            Employee owner = employeeSessionBeanLocal.getEmployee("System");
            messageSessionBeanLocal.addMessage("System", selectedSalesOrder.getJob().getEmployee().getUserId(), "Sales order rejected",
                    "Sales order for job: " + selectedSalesOrder.getJob().getJobId() + " for customer " + selectedSalesOrder.getJob().getCustomer().getCompany() + ". Please seek your in-charge for follow up action."
                    + "<p><hr/><p>This is a system generated message, no reply is required.", owner);

            owner = employeeSessionBeanLocal.getEmployee(selectedSalesOrder.getJob().getEmployee().getUserId());
            messageSessionBeanLocal.addMessage("System", selectedSalesOrder.getJob().getEmployee().getUserId(), "Sales order rejected",
                    "Sales order for job: " + selectedSalesOrder.getJob().getJobId() + " for customer " + selectedSalesOrder.getJob().getCustomer().getCompany() + ". Please seek your in-charge for follow up action."
                    + "<p><hr/><p>This is a system generated message, no reply is required.", owner);

            ArrayList<String> al = new ArrayList<String>();
            al.add("Sales order rejected");
            al.add("You have successfully rejected a sales order. Please advice the executive for follow up action.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("index.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void view(ActionEvent e) {
        try {
            if (selectedPurchaseOrder != null) {
                userSessionManagerBean.setSelectedPurchaseOrder(selectedPurchaseOrder);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/viewPurchaseOrder.xhtml"); //redirect to viewPurchaseOrder.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a purchase order before continuing.", ""));
            }

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void createSalesOrder(ActionEvent e) {
        try {
            if (selectedQuotation.getQuotationItems().size() > 0) {
                //get all quotations of the job
                List<Quotation> quotations = new ArrayList<Quotation>();
                quotations = selectedJob.getQuotations();

                //set all other quotations to expired
                //set the quotation that was used to convert to sales order as converted
                for (Quotation q : quotations) {
                    if (q.getId() != selectedQuotation.getId()) {
                        salesOrderSessionBeanLocal.updateQuotation(q.getId(), "Expired");
                    }
                }
                salesOrderSessionBeanLocal.updateQuotation(selectedQuotation.getId(), "Converted");
                purchaseOrderSessionBeanLocal.updatePurchaseOrder(selectedPurchaseOrder.getId(), "Converted");

                //update job 
                jobSessionBeanLocal.updateJob(selectedJob.getJobId(), selectedJob.getCustomer().getCustId(), selectedJob.getEmployee().getUserId(),
                        selectedJob.getQuotations(), selectedJob.getJobDate(), selectedQuotation.getId(), selectedJob.getDescription(), selectedJob.getType(), selectedPurchaseOrder.getId());

                //create sales order
                salesOrderSessionBeanLocal.addSalesOrder(selectedJob.getJobId(), "Pending", "Pending", "Pending Approval", getRemark());

                logSessionBeanLocal.addLog("Add sales order", "Sales record created for purchase order: " + selectedPurchaseOrder.getPoNumber(), "addSalesOrder.xhtml", userSessionManagerBean.getUserId());

                ArrayList<String> al = new ArrayList<String>();
                al.add("Sales order created");
                al.add("You have successfully created a sales order. This sales order has been added to the pending list for manager's approval.");
                al.add("Click on the link to return to ");
                al.add("continue");
                al.add("Web_Sales/searchJob.xhtml");
                userSessionManagerBean.setSelectedItem(al);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/success.xhtml"); //redirect to searchSalesOrders.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "You cannot create a sales order with a quotation that has no items.", ""));
            }
        } catch (Exception ex) {
            System.out.println("CREATE SALES ORDER EXCEPTION");
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void onRowSelect(SelectEvent event) {
        try {
            if (event.getComponent().getId().equals("salesOrders")) {
                userSessionManagerBean.setSelectedSalesOrder(selectedSalesOrder);
            } else if (event.getComponent().getId().equals("salesOrders2")) {
                try { //reload page on select of salesOrders2
                    purchaseItems = selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems();

                    userSessionManagerBean.setPurchaseItems(purchaseItems);
                    userSessionManagerBean.setSelectedSalesOrder(selectedSalesOrder);

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                            + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort()
                            + "/MerlionERP-war/Web_Sales/cancelSalesOrder.xhtml");
                } catch (Exception ex) {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
                }
            } else if (event.getComponent().getId().equals("mySalesOrders")) {
                trackingItems = selectedSalesOrder.getTrackingItems();
            } else if (event.getComponent().getId().equals("allSalesOrders")) {
                trackingItems = selectedSalesOrder.getTrackingItems();
            } else {
                userSessionManagerBean.setSelectedPurchaseOrder(selectedPurchaseOrder);
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void onRowUnselect(UnselectEvent event) {
        try {
            if (event.getComponent().getId().equals("salesOrders")) {
                userSessionManagerBean.setSelectedSalesOrder(null);
            } else if (event.getComponent().getId().equals("salesOrders2")) { //if cancelSalesOrder's salesOrders datatable called
                selectedSalesOrder = null;
                purchaseItems = null;
                selectedPurchaseItem = null;
            } else if (event.getComponent().getId().equals("purchaseItems")) { //if cancelSalesOrder's purchaseItems datatable called
                selectedPurchaseItem = null;
            } else {
                userSessionManagerBean.setSelectedPurchaseOrder(null);
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    /**
     * @return the loadAddSalesOrderPage
     */
    public String getLoadAddSalesOrderPage() {
        selectedJob = userSessionManagerBean.getSelectedJob();
        selectedQuotation = userSessionManagerBean.getSelectedQuotation();
        selectedPurchaseOrder = userSessionManagerBean.getSelectedPurchaseOrder();

        remark = compute();
        if (toReject) {
            toApprove = false;
        } else {
            remark = "";
        }


        return null;
    }

    /**
     * @return the loadSalesOrdersPage
     */
    public String getLoadSalesOrdersPage() {
        setSalesOrders(salesOrderSessionBeanLocal.getSalesOrders("Pending Approval"));
        setSalesOrdersSize(getSalesOrders().size());

        return null;
    }

    /**
     * @return the loadViewSalesOrderPage
     */
    public String getLoadViewSalesOrderPage() {
        selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder();

        Job j = selectedSalesOrder.getJob();

        selectedQuotation = j.getSelectedQuotation();
        selectedPurchaseOrder = selectedSalesOrder.getJob().getPurchaseOrder();
        remark = compute();

        return null;
    }

    /**
     * @param loadViewSalesOrderPage the loadViewSalesOrderPage to set
     */
    public void setLoadViewSalesOrderPage(String loadViewSalesOrderPage) {
        this.loadViewSalesOrderPage = loadViewSalesOrderPage;
    }

    /**
     * @return the loadViewPurchaseOrderPage
     */
    public String getLoadViewPurchaseOrderPage() {
        selectedPurchaseOrder = userSessionManagerBean.getSelectedPurchaseOrder();

        return null;
    }

    /**
     * @return the loadSearchPurchaseOrdersPage
     */
    public String getLoadSearchPurchaseOrdersPage() {
        setPurchaseOrders2(salesOrderSessionBeanLocal.getPurchaseOrders(
                userSessionManagerBean.getUserId(), "Pending"));

        this.setPurchaseOrdersCount2(purchaseOrders2.size());

        return null;
    }

    public String compute() {
        ArrayList<PurchaseItem> poi;
        ArrayList<QuotationItem> qi;
        String rmk = "";
        if (selectedSalesOrder != null) {

            //from viewSalesOrder.xhtml
            rmk = selectedSalesOrder.getJob().getEmployee().getName() + ":\n" + selectedSalesOrder.getRemark();
            rmk += "\n------------------------------------------------------------------------------------------------------";
            poi = new ArrayList(selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems());
            qi = new ArrayList(selectedSalesOrder.getJob().getSelectedQuotation().getQuotationItems());
        } else {
            //from addSalesOrder.xhtml
            poi = new ArrayList(selectedPurchaseOrder.getPurchaseItems());
            qi = new ArrayList(selectedQuotation.getQuotationItems());
        }


        Collections.sort(poi);
        Collections.sort(qi);

        rmk += "\nCompiler result:";
        double error = 0;
        int current = 1;
        if (poi.size() == qi.size()) {
            for (int i = 0; i < poi.size(); i++) {

                rmk += "\n\nChecking item " + current + " :" + poi.get(i).getProduct().getName() + ", Unit price: "
                        + poi.get(i).getUnitPrice() + ", Quantity:" + poi.get(i).getQuantity() + ", Shipping rate:"
                        + poi.get(i).getShippingRate();

                if (poi.get(i).getProduct().getCode().compareTo(qi.get(i).getProduct().getCode()) != 0) {
                    rmk += "\n>Dispute: Product mismatch\n>>Offered:" + qi.get(i).getProduct().getName();
                    error += 1.0;
                } else if (poi.get(i).getUnitPrice() != qi.get(i).getUnitPrice()) {
                    rmk += "\n>Dispute: Unit price mistmatch\n>>Offered:" + qi.get(i).getUnitPrice();
                    error += 1.0;
                } else if (poi.get(i).getQuantity() != qi.get(i).getQuantity()) {
                    rmk += "\n>Dispute: Quantity mismatch\n>>Offered:" + qi.get(i).getQuantity();
                    error += 1.0;
                } else if (poi.get(i).getShippingRate() - qi.get(i).getShippingRate() != 0) {
                    rmk += "\n>Dispute: Shipping rate mistmatch\n>>Offered:" + qi.get(i).getShippingRate();
                    error += 1.0;
                } else {
                    rmk += "\n>Clean record";
                }

                current++;
            }
        } else {
            error = poi.size();
            rmk += "Dispute: Item size mismatch/n";
        }

        rmk += "\n------------------------------------------------------------------------------------------------------\n";
        Double percentError = (error / poi.size());

        if (percentError > 0.8) {
            rmk += "Severity:MAJOR";
            toReject = true;
        } else if (percentError > 0.5) {
            rmk += "Severity:MINOR";
            toReject = true;
        } else if (percentError > 0.2) {
            rmk += "Severity:NEGLIGIBLE";
            toReject = true;
        } else {
            rmk += "Severity:CLEAN";
            toReject = false;
        }

        return rmk;
    }

    public double round(double valueToRound, int numberOfDecimalPlaces) {
        double multiplicationFactor = Math.pow(10, numberOfDecimalPlaces);
        double interestedInZeroDPs = valueToRound * multiplicationFactor;

        return Math.round(interestedInZeroDPs) / multiplicationFactor;
    }

    public void recalculateCredit(Credit credit, PurchaseOrder purchaseOrder, Invoice invoice) {
        Double accountsPayable = credit.getAccountsPayable();
        Double totalAmount = credit.getTotalAmount();
        Double outstandingScore = credit.getOutstandingScore();

        Double deposit = credit.getDeposit();

        Integer totalPayments = credit.getTotalPayments();
        Integer paymentsPaidLessThan30 = credit.getPaymentsPaidLessThan30();
        Integer paymentsPaidLate30to59 = credit.getPaymentsPaidLate30to59();
        Integer paymentsPaidLate60to89 = credit.getPaymentsPaidLate60to89();
        Integer paymentsPaidLaterThan90 = credit.getPaymentsPaidLaterThan90();
        Double paymentScore = credit.getPaymentScore();

        Double creditScore = credit.getCreditScore();
        creditScore -= outstandingScore;
        creditScore -= paymentScore;

        Double creditRate = purchaseOrder.getCreditRate();
        creditRate = creditRate / 100;
        Double paymentRate = 1 - creditRate;

        if (selectedPurchaseItem.getStatus().equals("Pending Advance Payment")) { //if have not received any payment
            //reduce credit accounts payable
            accountsPayable -= selectedPurchaseItem.getSubTotal();

            //reduce credit total amount
            totalAmount -= selectedPurchaseItem.getSubTotal();
        } else if (selectedPurchaseItem.getStatus().equals("Pending Final Payment")) { //already received an advance payment beforehand
            //reduce credit accounts payable
            accountsPayable -= round(creditRate * selectedPurchaseItem.getSubTotal(), 2);

            //reduce credit deposit
            deposit -= round(paymentRate * selectedPurchaseItem.getSubTotal(), 2);

            //reduce credit total amount
            totalAmount -= selectedPurchaseItem.getSubTotal();

            //get the payment record that was newly added
            Payment payment = creditSessionBeanLocal.getPayment(invoice.getId());

            //recalculate credit information - start
            //check if payment made within 30 days of invoice date
            Calendar cal1 = Calendar.getInstance();
            Calendar cal2 = Calendar.getInstance();

            cal2.setTime(payment.getPaymentDate()); //get date of payment
            cal1.setTime(invoice.getInvoiceDate());
            cal1.add(cal1.DAY_OF_YEAR, 30); //add 30 days to invoice date

            if (cal2.compareTo(cal1) < 0) { //payment made within 30 days of invoice date
                paymentsPaidLessThan30--; //decrement payments paid in less than 30 days

                credit.setPaymentsPaidLessThan30(paymentsPaidLessThan30);
            } else { //payment made 30 days after invoice date
                cal1.setTime(invoice.getInvoiceDate());
                cal1.add(cal1.DAY_OF_YEAR, 60);

                if (cal2.compareTo(cal1) < 0) { //payment made within 30 to 59 days
                    paymentsPaidLate30to59--; //decrement payments paid within 30 to 59 days

                    credit.setPaymentsPaidLate30to59(paymentsPaidLate30to59);
                } else { //payment made 60 days after invoice date
                    cal1.setTime(invoice.getInvoiceDate());
                    cal1.add(cal1.DAY_OF_YEAR, 90);

                    if (cal2.compareTo(cal1) < 0) { //payment made within 60 to 89 days
                        paymentsPaidLate30to59--; //decrement payments paid within 60 to 89 days

                        credit.setPaymentsPaidLate30to59(paymentsPaidLate30to59);
                    } else { //payments made after 90 days
                        paymentsPaidLaterThan90--; //decrement payments paid after 90 days

                        credit.setPaymentsPaidLaterThan90(paymentsPaidLaterThan90);
                    }
                }
            }
        }
        totalPayments--; //decrement total payments

        //start of recalculation PO figures
        Double actual = 100 - selectedPurchaseItem.getDiscount();
        actual = actual / 100;

        Integer piCases = selectedPurchaseItem.getQuantity() / 240;
        if (selectedPurchaseItem.getQuantity() - (piCases * 240) > 0) {
            piCases++;
        }

        Double piSubTotal = selectedPurchaseItem.getSubTotal();
        Double piTotalShipping = piCases * selectedPurchaseItem.getShippingRate();

        Double poTotalShipping = purchaseOrder.getShippingCost();
        Double poSubTotal = purchaseOrder.getCost();
        Double poTotalAmount = purchaseOrder.getTotalAmount();

        poTotalShipping -= piTotalShipping;
        poTotalAmount -= piSubTotal;
        poSubTotal -= (piSubTotal - piTotalShipping);

        purchaseOrder.setShippingCost(poTotalShipping);
        purchaseOrder.setCost(poSubTotal);
        purchaseOrder.setTotalAmount(poTotalAmount);
        //end of recalculation of PO figures

        //start of recalculation of outstanding score
        if (accountsPayable > totalAmount) {
            outstandingScore = round(0.00, 2);
        } else {
            double num1 = (accountsPayable / totalAmount) * 100;
            num1 = 100 - num1;
            outstandingScore = 0.4 * num1;
            outstandingScore = round(outstandingScore, 2);
        }
        //end of recalculation of outstanding score

        //start of recalculation of payment score
        if (totalPayments == 0 && paymentsPaidLessThan30 == 0 && paymentsPaidLate30to59 == 0 && paymentsPaidLate60to89 == 0
                && paymentsPaidLaterThan90 == 0) { //if customer has not made any payments before
            paymentScore = round(0.00, 2); //give him 0 paymentScore
        } else {
            double num1 = (paymentsPaidLate30to59 / totalPayments) * 20;
            double num2 = (paymentsPaidLate60to89 / totalPayments) * 30;
            double num3 = (paymentsPaidLaterThan90 / totalPayments) * 50;

            paymentScore = 100 - num3 - num2 - num1;
            paymentScore = 0.4 * paymentScore;
            paymentScore = round(paymentScore, 2);
        }
        //end of recalculation of payment score

        //start of recalculation of credit score
        creditScore += paymentScore;
        creditScore += outstandingScore;
        //end of recalculation of credit score

        credit.setTotalPayments(totalPayments);
        credit.setTotalAmount(totalAmount);
        credit.setAccountsPayable(accountsPayable);
        credit.setCreditScore(creditScore);
        credit.setOutstandingScore(outstandingScore);
        credit.setPaymentScore(paymentScore);
        credit.setDeposit(deposit);

        //update credit account
        creditSessionBeanLocal.updateCredit(credit.getId(), credit);
    }

    public void cancelPurchaseItem() {
        //get selectedSalesOrder from session
        selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder();

        //get corresponding purchase order
        PurchaseOrder purchaseOrder = selectedSalesOrder.getJob().getPurchaseOrder();

        //get corresponding customer's credit account
        Credit credit = selectedCustomer.getCredit();

        //get all invoices belonging to the selectedPurchaseItem
        List<Invoice> invoices = creditSessionBeanLocal.getInvoices(selectedPurchaseItem.getId());

        if (selectedPurchaseItem.getStatus().equals("Pending Advance Payment")) { //if purchase item is still pending
            recalculateCredit(credit, purchaseOrder, null);         //advance payment

            //update invoice status to invalid
            for (Invoice i : invoices) {
                creditSessionBeanLocal.updateInvoice(i.getId(), "Invalid");
            }
        } else if (selectedPurchaseItem.getStatus().equals("Pending Final Payment")) { //if purchase item is only 
            Invoice invoice = null;                                 //waiting for final payment

            for (Invoice i : invoices) {
                if (i.getStatus().equals("Paid")) {
                    invoice = i;
                }

                creditSessionBeanLocal.updateInvoice(i.getId(), "Invalid"); //update invoice status to invalid
                creditSessionBeanLocal.updatePayment(i.getId(), "Refunded"); //update payment status to refunded

                //start of send refund email to customer
                EmailManager em = new EmailManager();
                try {
                    String subject = "Refund of payment after cancellation of order item";

                    String msg = "Dear " + selectedCustomer.getCompany() + ",\n\n";

                    msg += "Invoice No.: " + invoice.getId() + "\n";

                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                    StringBuilder sb = new StringBuilder(sdf.format(invoice.getInvoiceDate()));
                    NumberFormat nf = NumberFormat.getCurrencyInstance();

                    //get the payment record corresponding to the invoice
                    Payment payment = creditSessionBeanLocal.getPayment(invoice.getId());

                    msg += "Invoice Date: " + sb + "\n";
                    msg += "Purchase Item: " + selectedPurchaseItem.getProduct().getName() + "\n";
                    msg += "Purchase Quantity: " + selectedPurchaseItem.getQuantity() + "\n";
                    msg += "Payment Date: " + sdf.format(payment.getPaymentDate()) + "\n";
                    msg += "Payment Amount: " + nf.format(payment.getAmountPaid()) + "\n";

                    if (cancelReason.equals("UTF")) {
                        msg += "Penalty: 0%\n";
                        msg += "Penalty Amount: $0.00\n";
                        msg += "Refund Amount: $0.00\n\n";
                    } else {
                        msg += "Penalty: 20%\n";
                        msg += "Penalty Amount: " + nf.format(payment.getAmountPaid() * 0.2) + "\n";
                        msg += "Refund Amount: " + nf.format(payment.getAmountPaid() * 0.8) + "\n\n";
                    }

                    msg += "Regards,\nMerlion Food Limited";

                    String sender = "mf.merlionerp@gmail.com";
                    String receiver = selectedCustomer.getEmail();
                    String password = "merlionfood";

                    System.out.println("Sending refund to " + receiver + "...");

                    em.sendEmail(subject, msg, sender, receiver, password);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                //end of send refund email to customer
            }

            recalculateCredit(credit, purchaseOrder, invoice);
        } else if (selectedPurchaseItem.getStatus().equals("Pending")) {
        }

        updatePurchaseItem();
    }

    public void updatePurchaseItem() {
        //update purchase item status
        creditSessionBeanLocal.updatePurchaseItem(selectedPurchaseItem.getId(), 0.0, "Cancelled");

        //log
        logSessionBeanLocal.addLog("Purchase item cancellation", "Purchase item cancelled: " + selectedPurchaseItem.getId(), "cancelSalesOrder.xhtml", userSessionManagerBean.getUserId());

        //retrieve sales order with updated purchaseItems
        selectedSalesOrder = salesOrderSessionBeanLocal.getSalesOrder(selectedSalesOrder.getId());

        Boolean isAllCancelled = true;
        //loop through all purchase items of the order
        for (PurchaseItem pi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
            if (!pi.getStatus().equals("Cancelled")) {
                isAllCancelled = false; //there is still one purchase item that is not cancelled
                break;
            }
        }

        //if all purchase items of the selectedSalesOrder are cancelled,
        //update sales order status to cancelled too
        if (isAllCancelled) {
            salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), "Cancelled");

            logSessionBeanLocal.addLog("Sales order cancellation", "Sales order cancelled: " + selectedSalesOrder.getId(), "cancelSalesOrder.xhtml", userSessionManagerBean.getUserId());
        }
    }

    public void cancelPurchaseItem(ActionEvent event) { //to cancel the selected purchase item
        if (selectedPurchaseItem != null) {
            if (!selectedPurchaseItem.getStatus().equals("Cancelled")) {
                if (selectedPurchaseItem.getIsDelivered() == false) {
                    if (cancelReason != null && !cancelReason.equals("")) {
                        try {
                            selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder();

                            if (selectedSalesOrder.getStatus().equals("Pending Deliveries and Payments")) { //already waiting for payments
                                cancelPurchaseItem();
                            } else { //still pending checks
                                updatePurchaseItem();
                            }

                            //clear session variables
                            userSessionManagerBean.setPurchaseItems(null);
                            userSessionManagerBean.setSelectedSalesOrder(null);

                            ArrayList<String> al = new ArrayList<String>();
                            al.add("Purchase item cancelled");
                            al.add("You have successfully cancelled a purchase item.");
                            al.add("Click on the link to return to ");
                            al.add("continue");
                            al.add("Web_Sales/searchCustomer.xhtml?request=cancelSalesOrder");
                            userSessionManagerBean.setSelectedItem(al);

                            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                                    + userSessionManagerBean.getServerName() + ":"
                                    + userSessionManagerBean.getServerPort()
                                    + "/MerlionERP-war/success.xhtml");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            FacesContext.getCurrentInstance().addMessage(null,
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
                        }
                    } else {
                        FacesContext.getCurrentInstance().addMessage(null,
                                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a reason for the cancellation of order item.", ""));
                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "The selected purchase item has already been delivered.", ""));
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "The selected purchase item has already been cancelled.", ""));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a purchase item before continuing.", ""));
        }
    }

    public void cancelSalesOrder(ActionEvent event) { //to cancel the selected sales order
        if (userSessionManagerBean.getSelectedSalesOrder() != null) {
            if (!cancelReason.equals("")) {
                selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder();

                try {
                    if (selectedSalesOrder.getStatus().equals("Pending Deliveries and Payments")) {

                        for (PurchaseItem pi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
                            selectedPurchaseItem = pi;

                            cancelPurchaseItem(); //update status, invalidate invoices and refund payment
                        }
                    } else {
                        for (PurchaseItem pi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
                            selectedPurchaseItem = pi;

                            updatePurchaseItem(); //just update status
                        }
                    }

                    //clear session variables
                    userSessionManagerBean.setPurchaseItems(null);
                    userSessionManagerBean.setSelectedSalesOrder(null);

                    ArrayList<String> al = new ArrayList<String>();
                    al.add("Sales order cancelled");
                    al.add("You have successfully cancelled a sales order.");
                    al.add("Click on the link to return to ");
                    al.add("continue");
                    al.add("Web_Sales/searchCustomer.xhtml?request=cancelSalesOrder");
                    userSessionManagerBean.setSelectedItem(al);

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                            + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort()
                            + "/MerlionERP-war/success.xhtml");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a reason for the cancellation of order.", ""));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a sales order before continuing.", ""));
        }
    }

    public void sendEmail(Double penalty, String type) {
    }

    public void rejectSalesOrderByExec(ActionEvent event) {
        jobSessionBeanLocal.rejectPurchaseOrder(selectedJob.getJobId());
        logSessionBeanLocal.addLog("Reject purchase order", "Purchase order rejected: " + selectedPurchaseOrder.getPoNumber(), "addSalesOrder.xhtml", userSessionManagerBean.getUserId());

        try {
            ArrayList<String> al = new ArrayList<String>();
            al.add("Purchase order rejected");
            al.add("You have successfully rejected a purchase order. Please contact the customer to send another purchase order for the quotation.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Sales/searchJob.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort()
                    + "/MerlionERP-war/success.xhtml"); //redirect to searchSalesOrders.xhtml
        } catch (Exception ex) {
        }
    }

    //JACKIE HERE
    public void resolve(ActionEvent event) {
        Warehouse wh = warehouseSessionBeanLocal.getWarehouse(Long.parseLong("1000"));

        for (PurchaseItem poi : selectedSalesOrder.getJob().getPurchaseOrder().getPurchaseItems()) {
            productionScheduleSessionBeanLocal.reservePurchaseItem(wh, poi.getId(), productionScheduleSessionBeanLocal.getProductionSchedules());
        }
//        salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), "Pending Credit Check");
        salesOrderSessionBeanLocal.updateQuotation(selectedSalesOrder.getJob().getSelectedQuotation().getId(), "Approved");
        purchaseOrderSessionBeanLocal.updatePurchaseOrder(selectedSalesOrder.getJob().getPurchaseOrder().getId(), "Approved");
        TrackingItem ti = new TrackingItem();
        ti.setDescription("Production scheduled");
        salesOrderSessionBeanLocal.updateSalesOrder(selectedSalesOrder.getId(), ti);
        salesOrderSessionBeanLocal.updateAtpStatus(selectedSalesOrder.getId(), "Passed");


        try {
            logSessionBeanLocal.addLog("Update sales order", "Sales order date confirmed: " + selectedSalesOrder.getId(), "updateSalesOrder.xhtml", userSessionManagerBean.getUserId());
            ArrayList<String> al = new ArrayList<String>();
            al.add("Sales order dates confirmed");
            al.add("You have successfully confirmed the dates for the sales order.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Sales/searchJob.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
        }


    }

    public void reject(ActionEvent event) {
    }

    /**
     * @return the loadCancelSalesOrderPage
     */
    public String getLoadCancelSalesOrderPage() {
        setSelectedCustomer(userSessionManagerBean.getCustomer());

        cancelReason = "";

        List<SalesOrder> temp = salesOrderSessionBeanLocal.getSalesOrders("Pending Deliveries and Payments");
        List<SalesOrder> temp2 = salesOrderSessionBeanLocal.getSalesOrders("Pending Credit Check");
        List<SalesOrder> temp3 = salesOrderSessionBeanLocal.getSalesOrders("Pending ATP Check");
        List<SalesOrder> temp4 = salesOrderSessionBeanLocal.getSalesOrders("Pending Approval");

        //populate all sales orders from above into salesOrders2
        for (SalesOrder so : temp) {
            if (so.getJob().getCustomer().getId() == selectedCustomer.getCustId()) {
                salesOrders2.add(so);
            }
        }

        for (SalesOrder so : temp2) {
            if (so.getJob().getCustomer().getId() == selectedCustomer.getCustId()) {
                salesOrders2.add(so);
            }
        }

        for (SalesOrder so : temp3) {
            if (so.getJob().getCustomer().getId() == selectedCustomer.getCustId()) {
                salesOrders2.add(so);
            }
        }

        for (SalesOrder so : temp4) {
            if (so.getJob().getCustomer().getId() == selectedCustomer.getCustId()) {
                salesOrders2.add(so);
            }
        }

        if (userSessionManagerBean.getSelectedSalesOrder() != null) {
            selectedSalesOrder = userSessionManagerBean.getSelectedSalesOrder();
        }

        if (userSessionManagerBean.getPurchaseItems() != null) {
            setPurchaseItems(userSessionManagerBean.getPurchaseItems());
        }

        return null;
    }

    /**
     * @param loadCancelSalesOrderPage the loadCancelSalesOrderPage to set
     */
    public void setLoadCancelSalesOrderPage(String loadCancelSalesOrderPage) {
        this.loadCancelSalesOrderPage = loadCancelSalesOrderPage;
    }

    /**
     * @return the selectedCustomer
     */
    public Customer getSelectedCustomer() {
        return selectedCustomer;
    }

    /**
     * @param selectedCustomer the selectedCustomer to set
     */
    public void setSelectedCustomer(Customer selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    /**
     * @return the purchaseItems
     */
    public List<PurchaseItem> getPurchaseItems() {
        return purchaseItems;
    }

    /**
     * @param purchaseItems the purchaseItems to set
     */
    public void setPurchaseItems(List<PurchaseItem> purchaseItems) {
        this.purchaseItems = purchaseItems;
    }

    /**
     * @return the selectedPurchaseItem
     */
    public PurchaseItem getSelectedPurchaseItem() {
        return selectedPurchaseItem;
    }

    /**
     * @param selectedPurchaseItem the selectedPurchaseItem to set
     */
    public void setSelectedPurchaseItem(PurchaseItem selectedPurchaseItem) {
        this.selectedPurchaseItem = selectedPurchaseItem;
    }

    /**
     * @return the salesOrders2
     */
    public List<SalesOrder> getSalesOrders2() {
        return salesOrders2;
    }

    /**
     * @param salesOrders2 the salesOrders2 to set
     */
    public void setSalesOrders2(List<SalesOrder> salesOrders2) {
        this.salesOrders2 = salesOrders2;
    }

    /**
     * @return the cancelReason
     */
    public String getCancelReason() {
        return cancelReason;
    }

    /**
     * @param cancelReason the cancelReason to set
     */
    public void setCancelReason(String cancelReason) {
        this.cancelReason = cancelReason;
    }

    /**
     * @return the loadMySalesOrders
     */
    public String getLoadMySalesOrders() {
        selectedCustomer = userSessionManagerBean.getCustomer();

        salesOrders = salesOrderSessionBeanLocal.getSalesOrdersByCustomer(selectedCustomer.getCustId());

        return null;
    }

    /**
     * @param loadMySalesOrders the loadMySalesOrders to set
     */
    public void setLoadMySalesOrders(String loadMySalesOrders) {
        this.loadMySalesOrders = loadMySalesOrders;
    }

    /**
     * @return the trackingItems
     */
    public List<TrackingItem> getTrackingItems() {
        return trackingItems;
    }

    /**
     * @param trackingItems the trackingItems to set
     */
    public void setTrackingItems(List<TrackingItem> trackingItems) {
        this.trackingItems = trackingItems;
    }

    /**
     * @return the loadSalesOrders
     */
    public String getLoadSalesOrders() {
        selectedCustomer = userSessionManagerBean.getCustomer();

        salesOrders = salesOrderSessionBeanLocal.getSalesOrders();

        return null;
    }

    /**
     * @param loadSalesOrders the loadSalesOrders to set
     */
    public void setLoadSalesOrders(String loadSalesOrders) {
        this.loadSalesOrders = loadSalesOrders;
    }

    /**
     * @return the toApprove
     */
    public Boolean getToApprove() {
        return toApprove;
    }

    /**
     * @param toApprove the toApprove to set
     */
    public void setToApprove(Boolean toApprove) {
        this.toApprove = toApprove;
    }

    /**
     * @return the toReject
     */
    public Boolean getToReject() {
        return toReject;
    }

    /**
     * @param toReject the toReject to set
     */
    public void setToReject(Boolean toReject) {
        this.toReject = toReject;
    }

    /**
     * @param loadUpdateSalesorder the loadUpdateSalesorder to set
     */
    public void setLoadUpdateSalesorder(String loadUpdateSalesorder) {
        this.loadUpdateSalesorder = loadUpdateSalesorder;
    }

    /**
     * @return the tis
     */
    public ArrayList<TrackingItem> getTis() {
        return tis;
    }

    /**
     * @param tis the tis to set
     */
    public void setTis(ArrayList<TrackingItem> tis) {
        this.tis = tis;
    }

    public void tracking(ActionEvent event) {
        try {

            SalesOrder salesOrder = salesOrderSessionBeanLocal.getSalesOrder(Long.parseLong(salesOrderNumber));
            System.out.println(customerEmail);
            System.out.println(salesOrder);
            System.out.println(salesOrder.getJob().getPurchaseOrder().getCustomer().getEmail());
            if (salesOrder.getJob().getPurchaseOrder().getCustomer().getEmail().compareTo(customerEmail) == 0) {
                tis = new ArrayList(salesOrder.getTrackingItems());
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Records not found", ""));
            }
        } catch (Exception ex) {
        }
    }

    /**
     * @return the customerEmail
     */
    public String getCustomerEmail() {
        return customerEmail;
    }

    /**
     * @param customerEmail the customerEmail to set
     */
    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    /**
     * @return the salesOrderNumber
     */
    public String getSalesOrderNumber() {
        return salesOrderNumber;
    }

    /**
     * @param salesOrderNumber the salesOrderNumber to set
     */
    public void setSalesOrderNumber(String salesOrderNumber) {
        this.salesOrderNumber = salesOrderNumber;
    }
}
